from flask import Blueprint, jsonify, request
import os
import json

# 创建蓝图对象
stock_group = Blueprint('stock_group', __name__)

# 股票组合文件路径
STOCK_GROUP_FILE = 'data/stock_groups.json'

def ensure_data_file():
    """确保数据文件存在，如果不存在则创建一个空的数据文件"""
    os.makedirs(os.path.dirname(STOCK_GROUP_FILE), exist_ok=True)
    if not os.path.exists(STOCK_GROUP_FILE):
        with open(STOCK_GROUP_FILE, 'w', encoding='utf-8') as f:
            json.dump([], f, ensure_ascii=False)

def read_stock_groups():
    """读取所有股票组合"""
    ensure_data_file()
    with open(STOCK_GROUP_FILE, 'r', encoding='utf-8') as f:
        return json.load(f)

def write_stock_groups(data):
    """写入股票组合到文件"""
    ensure_data_file()
    with open(STOCK_GROUP_FILE, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=4)

@stock_group.route('/stock_groups', methods=['GET'])
def get_all_stock_groups():
    """获取所有股票组合"""
    try:
        groups = read_stock_groups()
        return jsonify(groups)
    except Exception as e:
        return jsonify({'error': f'获取股票组合失败: {str(e)}'}), 500

@stock_group.route('/stock_groups/<int:group_id>', methods=['GET'])
def get_stock_group(group_id):
    """获取单个股票组合"""
    try:
        groups = read_stock_groups()
        if 0 <= group_id < len(groups):
            return jsonify(groups[group_id])
        else:
            return jsonify({'error': f'未找到组合ID: {group_id}'}), 404
    except Exception as e:
        return jsonify({'error': f'获取股票组合失败: {str(e)}'}), 500

@stock_group.route('/stock_groups', methods=['POST'])
def add_stock_group():
    """添加新的股票组合"""
    try:
        new_group = request.json
        if not new_group or 'name' not in new_group or 'codes' not in new_group:
            return jsonify({'error': '组合名称和股票代码是必需的参数'}), 400
        
        groups = read_stock_groups()
        
        # 检查是否已存在相同名称的组合
        if any(g['name'] == new_group['name'] for g in groups):
            return jsonify({'error': f'组合名称已存在: {new_group["name"]}'}), 409
        
        # 确保codes是一个列表
        if not isinstance(new_group['codes'], list):
            return jsonify({'error': '股票代码必须是一个列表'}), 400
        
        groups.append(new_group)
        write_stock_groups(groups)
        
        return jsonify({'id': len(groups) - 1, **new_group}), 201
    except Exception as e:
        return jsonify({'error': f'添加股票组合失败: {str(e)}'}), 500

@stock_group.route('/stock_groups/<int:group_id>', methods=['PUT'])
def update_stock_group(group_id):
    """更新股票组合"""
    try:
        updated_group = request.json
        if not updated_group or 'name' not in updated_group or 'codes' not in updated_group:
            return jsonify({'error': '组合名称和股票代码是必需的参数'}), 400
        
        groups = read_stock_groups()
        
        # 检查组合ID是否有效
        if not (0 <= group_id < len(groups)):
            return jsonify({'error': f'未找到组合ID: {group_id}'}), 404
        
        # 检查是否与其他组合名称冲突
        if any(i != group_id and g['name'] == updated_group['name'] for i, g in enumerate(groups)):
            return jsonify({'error': f'组合名称已存在: {updated_group["name"]}'}), 409
        
        # 确保codes是一个列表
        if not isinstance(updated_group['codes'], list):
            return jsonify({'error': '股票代码必须是一个列表'}), 400
        
        groups[group_id] = updated_group
        write_stock_groups(groups)
        
        return jsonify({'id': group_id, **updated_group})
    except Exception as e:
        return jsonify({'error': f'更新股票组合失败: {str(e)}'}), 500

@stock_group.route('/stock_groups/<int:group_id>', methods=['DELETE'])
def delete_stock_group(group_id):
    """删除股票组合"""
    try:
        groups = read_stock_groups()
        
        # 检查组合ID是否有效
        if not (0 <= group_id < len(groups)):
            return jsonify({'error': f'未找到组合ID: {group_id}'}), 404
        
        deleted_group = groups.pop(group_id)
        write_stock_groups(groups)
        
        return jsonify({'message': f'已删除组合: {deleted_group["name"]}', 'deleted': deleted_group})
    except Exception as e:
        return jsonify({'error': f'删除股票组合失败: {str(e)}'}), 500 